/*
    Promise.allSettled()方法返回一个在所有给定的 promise 都已经fulfilled或rejected后的 promise，
    并带有一个对象数组，每个对象表示对应的 promise 结果

    {
         status: 'fulfilled' | 'rejected',
         value | reason
    }
*/

function myPromiseAllSelected(promises) {
    if (!Array.isArray(promises)) {
        throw new Error('The arguments must to be an array');
    };

    return new Promise(function (resolve, reject) {
        let res = [];
        let count = 0;
        promises.forEach((s, index) => {
            Promise.resolve(s)
                .then(val => {
                    res[index] = {
                        status: 'fulfilled',
                        value: val,
                    }
                    count++;
                    if (count === promises.length) {
                        resolve(res);
                    };
                }).catch(err => {
                    res[index] = {
                        status: 'rejected',
                        reason: err,
                    };
                    count++;
                    if (count === promises.length) {
                        resolve(res);
                    };
                });
        });
    })
};


// test

let p1 = Promise.resolve(3);
let p2 = Promise.reject(2);

Promise.allSettled([p1, p2]).then(val => {
    console.log(val)
}). catch(err => {
    console.log(err)
});  

/*
    [
        { status: 'fulfilled', value: 3 },
        { status: 'rejected', reason: 2 }
    ]
*/ 


myPromiseAllSelected([p1,p2]).then(res => console.log(res), err => console.log(err))